// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database();

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  try {
    var block = await db.collection('block').where({
      user_id: wxContext.OPENID,
    }).get();
    if (block.data[0].block == true) {
      return {
        messages: new Array(),
      }
    } else {

      var messages = new Array();

      const total = await db.collection('message').where({
        user_id: wxContext.OPENID,
      }).count();

      const size = total.total;
      for (let i = 0; i <= size; i++) {
        var message = await db.collection('message').where({
          message_id: i,
          user_id: wxContext.OPENID,
        }).get();
        if (message.data[0] != null) {
          //标为已读
          await db.collection('message').doc(message.data[0]._id).update({
            data: {
              read: true,
            }
          });
          messages.push(message.data[0])
        }
      }
      return {
        messages: messages,
      }
    }
  } catch (e) {
    console.error(e);
  }
}